package com.zbj.springboot.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
 * DataSourceConfig
 *
 * @author weigang
 * @create 2018-04-16
 **/
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Value("${jdbc.master.url}")
    String dbMaterUrl;

    @Value("${jdbc.master.username}")
    String dbMaterUsername;

    @Value("${jdbc.master.password}")
    String dbMaterPassword;

    @Value("${jdbc.slave.url}")
    String dbSlaveUrl;

    @Value("${jdbc.slave.username}")
    String dbSlaveUsername;

    @Value("${jdbc.slave.password}")
    String dbSlavePassword;

    @Bean(name = "dataSourceMaster", initMethod = "init", destroyMethod = "close")
    @Qualifier("dataSourceMaster")
    @Primary
    public DruidDataSource dataSourceMaster() throws SQLException {
        return dataSource(dbMaterUrl, dbMaterUsername, dbMaterPassword);
    }

    @Bean(name = "sqlSessionFactoryMaster")
    @Primary
    public SqlSessionFactory sqlSessionFactoryBeanMater(@Qualifier("dataSourceMaster") DataSource dataSource, @Qualifier("pageHelper") PageHelper pageHelper) throws Exception {
        return sqlSessionFactory(dataSource, pageHelper);
    }

    @Bean(name = "dataSourceSlave", initMethod = "init", destroyMethod = "close")
    @Qualifier("dataSourceSlave")
    public DruidDataSource dataSourceSlave() throws SQLException {
        return dataSource(dbSlaveUrl, dbSlaveUsername, dbSlavePassword);
    }

    @Bean(name = "sqlSessionFactorySlave")
    public SqlSessionFactory sqlSessionFactoryBeanSlave(@Qualifier("dataSourceSlave") DataSource dataSource, @Qualifier("pageHelper") PageHelper pageHelper) throws Exception {
        return sqlSessionFactory(dataSource, pageHelper);
    }

    private SqlSessionFactory sqlSessionFactory(DataSource dataSource, PageHelper pageHelper) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath*:mybatis/xml/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resources);
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
        return sqlSessionFactoryBean.getObject();
    }

    private DruidDataSource dataSource(String url, String userName, String pwd) throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(pwd);
        dataSource.setMaxActive(10);
        dataSource.setInitialSize(10);
        dataSource.setMinIdle(10);
        dataSource.setTimeBetweenEvictionRunsMillis(10000);
        dataSource.setMinEvictableIdleTimeMillis(30000);
        dataSource.setValidationQuery("SELECT 'x'");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setRemoveAbandoned(true);
        dataSource.setRemoveAbandonedTimeout(1800);
        dataSource.setLogAbandoned(true);
        dataSource.setFilters("stat");
        dataSource.setConnectionProperties("druid.stat.slowSqlMillis=100");

        return dataSource;
    }

    @Bean(name = "pageHelper")
    public PageHelper pageHelper() {
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("dialect", "mysql");
        properties.setProperty("pageSizeZero", "true");
        properties.setProperty("reasonable", "true");
        pageHelper.setProperties(properties);
        return pageHelper;
    }


}
